//
//  FileUtil.swift
//  GreenDeal
//
//  Created by Moennig Q on 2023/3/7.
//

import UIKit

class FileUtil: NSObject {
    //createDir in documents of sandbox
    private func createDirInDocuments(_ dirName: String) -> String{
        let dirPath = APPConfig.documentsPath.appendingPathComponent(dirName)
        let fileManager = FileManager.default
        var isDir = ObjCBool(false)
        let isDirExist = fileManager.fileExists(atPath: dirPath, isDirectory: &isDir )
        //isDir is a output parameter
        if !(isDirExist && isDir.boolValue) {
            do {
                try fileManager.createDirectory(atPath: dirPath, withIntermediateDirectories: true, attributes: nil)
            } catch _ {
                NSLog("Create Directory [" + dirName + "] failed")
            }
        }
        return dirPath
        
    }
    func getServiceChecklistImagePath(_ fileName: String, fileSuffix: String = APPConfig.ImageSuffix) -> String{
        let folderPath = self.createDirInDocuments("GreenDeal/ServiceJob/\(ServiceDetailModelHelper.shared.serviceDetailModel.id)" + "/" + APPConfig.CheckListFolderName)
        return NSString(string: folderPath).appendingPathComponent(fileName + fileSuffix)
    }
    //版本1.5.0（包括1.5.0）以后，扫描Barcode时，生成barcode图片的路径
    func getPanelNumberImagePath(_ barcode: String) -> String{
        let folderPath = self.createDirInDocuments("GreenDeal/" + JobDetailModelHelper.shared.jobDetailModel.id + "/" + APPConfig.PanelNumberImagesDirName)
        return NSString(string: folderPath).appendingPathComponent(barcode + APPConfig.ImageSuffix)
    }
    func getInverterNumberImagePath(_ barcode: String) -> String{
        let folderPath = self.createDirInDocuments("GreenDeal/" + JobDetailModelHelper.shared.jobDetailModel.id + "/" + APPConfig.InverterNumberImagesDirName)
        return NSString(string: folderPath).appendingPathComponent(barcode + APPConfig.ImageSuffix)
    }
    //版本1.5.0（包括1.5.0）以后，生成checklist image type图片的路径
    func getChecklistImagePath(_ fileName: String, fileSuffix: String = APPConfig.ImageSuffix) -> String{
        let folderPath = self.createDirInDocuments("GreenDeal/" + JobDetailModelHelper.shared.jobDetailModel.id + "/" + APPConfig.CheckListFolderName)
        return NSString(string: folderPath).appendingPathComponent(fileName + fileSuffix)
    }
    //get real path when sandbox is changed because of upgrade app
    func getRealFilePath(_ oldPath: String)->String{
        let existFlag = FileManager.default.fileExists(atPath: oldPath)
        if !existFlag {
            let splits = oldPath.components(separatedBy: "Documents/")
            if splits.count > 1 {
                let newPath = APPConfig.documentsPath.appendingPathComponent(splits[1])
                return newPath
            }
        }
        return oldPath
    }
    func deleteSingleFile(_ relativePath: String){
        
        let filePath = APPConfig.documentsPath.appendingPathComponent(relativePath)
        let existFlag = FileManager.default.fileExists(atPath: filePath)
        if existFlag {
            do {
                try FileManager.default.removeItem(atPath: filePath)
            }catch let error as NSError {
                print(error.localizedDescription)
            }
        }
    }
    func deleteDirInDocument(_ dirName: String) {
        
        let fileManager = FileManager.default
        let folderPath =  APPConfig.documentsPath.appendingPathComponent(dirName)
        if fileManager.fileExists(atPath: folderPath) {
            do {
                
                let paths = try fileManager.contentsOfDirectory(atPath: folderPath)
                for path in paths
                {
                    try fileManager.removeItem(atPath: "\(folderPath)/\(path)")
                }
            } catch let error as NSError {
                print(error.localizedDescription)
            }
        }
        
    }
    
    func listFileInDir(_ dirName: String){
        let dirPath = APPConfig.documentsPath.appendingPathComponent(dirName)
        
        
        let fileManager = FileManager.default
        
        let fileList: [String] = try! fileManager.contentsOfDirectory(atPath: dirPath)
        
        print(fileList)
    }
}
